/**
 ****************************************************************************************
 *
 * @file proc.c
 *
 * @brief user procedure.
 *
 ****************************************************************************************
 */

#include "bledef.h"
#include "drvs.h"

#include "app.h"
#include "keys.h"
#include "hid_desc.h"
#include "app_user.h"

#if (DBG_PROC)
#include "dbg.h"
#define DEBUG(format, ...)    debug("<%s,%d>" format "\r\n", __MODULE__, __LINE__, ##__VA_ARGS__)
#else
#define DEBUG(format, ...)
#define debugHex(dat, len)
#endif

#define BLE_SLP_MS(ms)           ((ms) << 5)

/*
 * DEFINES
 ****************************************************************************************
 */

void user_procedure(void)
{
    uint32_t slpdur = ble_slpdur_get();
    
    #if (CFG_POWEROFF)
    // > 20ms
    if (slpdur > BLE_SLP_MS(20)/*640*/)
    {
        // Core enter poweroff mode
        if (ble_sleep(200, slpdur) == BLE_IN_SLEEP)
        {
            GPIO_DIR_SET_LO(KEY_COL_MSK);
            wakeup_io_sw(KEY_ROW_MSK, KEY_ROW_MSK);
            core_pwroff(CFG_WKUP_BLE_EN | CFG_WKUP_IO_EN | WKUP_IO_LATCH_N_BIT);
        }
    }
    else if (slpdur > 100)
    {
        // Core enter deepsleep mode
        if (ble_sleep(64, slpdur) == BLE_IN_SLEEP)
        {
            core_sleep(CFG_WKUP_BLE_EN);
        }
        
        keys_proc();
    }
    #else
    if ((slpdur > BLE_SLP_MS(10)/*320*/) && (ble_sleep(BLE_SLP_TWOSC, slpdur) == BLE_IN_SLEEP))
    {
        uint16_t core_wkup_en = (slpdur < BLE_SLP_MS(50)/*1600*/) ? (CFG_WKUP_BLE_EN) : (CFG_WKUP_BLE_EN | CFG_WKUP_IO_EN);
        
        uint16_t lpret = core_sleep(core_wkup_en);

        if (lpret & WKUP_ST_IO_BIT)
        {
            ble_wakeup();
        }
        
        os_judge_proc();
        
        keys_proc();
    }
    #endif //(CFG_SLEEP)
}
